package org.ielts.repository.course;

import java.util.List;

import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.Subqueries;
import org.ielts.domain.course.Content;
import org.ielts.domain.course.Subject;
import org.ielts.domain.query.SubjectQuery;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;
import com.yifeng.dao.HibernateRepository;

@Repository
public class SubjectRepository extends HibernateRepository<Subject, String> {

	public Page<Subject> findAll(SubjectQuery subjectQuery, Pageable pageable) {
		DetachedCriteria detachedCriteria = createDetachedCriteria();

		if (subjectQuery.hasBillingModel()) {
			detachedCriteria.add(Restrictions.eq("billingModel", subjectQuery.getBillingModel()));
		}

		if (subjectQuery.hasForm()) {
			detachedCriteria.add(Restrictions.eq("form", subjectQuery.getForm()));
		}

		if (subjectQuery.hasContents()) {
			DetachedCriteria dc = DetachedCriteria.forClass(Subject.class);
			dc.createAlias("contents", "c");
			dc.add(Restrictions.in("c.id", subjectQuery.getContents()));
			dc.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
			dc.setProjection(Projections.id());

			detachedCriteria.add(Subqueries.propertyIn("id", dc));
		}

		Page<Subject> subjects = pageByCriteria(detachedCriteria, pageable);

		return subjects;
	}

}
